<template>
  <div>
    <div id="chinaMap" style="width: 100%; height: 600px;"></div>
    <div class="radio-group">
      <!--      <button v-if="currentMap !== '中国'" @click="goToChinaMap">返回中国地图</button>-->
      <!--      <button v-if="previousAdcode.length > 0" @click="goToChinaMap">返回上一级</button>-->

      <el-button type="primary" v-if="previousAdcode.length > 0" @click="goToChinaMap">返回中国地图</el-button>
      <el-button type="primary" v-if="previousAdcode.length > 0" @click="goToPreviousArea">返回上一级</el-button>

    </div>

    <!--  返回上一级按钮  -->
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'ChinaMap',
  props: {
    regionList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null,
      currentMap: '中国', // 默认显示中国地图
      currentAdcode: '100000_full', // 默认的行政代码
      currentLevel: 'country',
      previousAdcode: [], // 上一次的行政代码
      previousMap: [], // 上一次的地图名称
      previousLevel: [], // 上一次的级别
      // 省份数据
      provinceData: [
        { name: '北京市', adcode: 110000, value: 0 },
        { name: '天津市', adcode: 120000, value: 0 },
        { name: '河北省', adcode: 130000, value: 0 },
        { name: '山西省', adcode: 140000, value: 0 },
        { name: '内蒙古自治区', adcode: 150000, value: 0 },
        { name: '辽宁省', adcode: 210000, value: 0 },
        { name: '吉林省', adcode: 220000, value: 0 },
        { name: '黑龙江省', adcode: 230000, value: 0 },
        { name: '上海市', adcode: 310000, value: 0 },
        { name: '江苏省', adcode: 320000, value: 0 },
        { name: '浙江省', adcode: 330000, value: 0 },
        { name: '安徽省', adcode: 340000, value: 0 },
        { name: '福建省', adcode: 350000, value: 0 },
        { name: '江西省', adcode: 360000, value: 0 },
        { name: '山东省', adcode: 370000, value: 0 },
        { name: '河南省', adcode: 410000, value: 0 },
        { name: '湖北省', adcode: 420000, value: 0 },
        { name: '湖南省', adcode: 430000, value: 0 },
        { name: '广东省', adcode: 440000, value: 0 },
        { name: '广西壮族自治区', adcode: 450000, value: 0 },
        { name: '海南省', adcode: 460000, value: 0 },
        { name: '重庆市', adcode: 500000, value: 0 },
        { name: '四川省', adcode: 510000, value: 0 },
        { name: '贵州省', adcode: 520000, value: 0 },
        { name: '云南省', adcode: 530000, value: 0 },
        { name: '西藏自治区', adcode: 540000, value: 0 },
        { name: '陕西省', adcode: 610000, value: 0 },
        { name: '甘肃省', adcode: 620000, value: 0 },
        { name: '青海省', adcode: 630000, value: 0 },
        { name: '宁夏回族自治区', adcode: 640000, value: 0 },
        { name: '新疆维吾尔自治区', adcode: 650000, value: 0 },
        { name: '台湾省', adcode: 710000, value: 0 },
        { name: '香港特别行政区', adcode: 810000, value: 0 },
        { name: '澳门特别行政区', adcode: 820000, value: 0 },
        { name: '', adcode: '100000_JD', value: 0 },
        { name: '南海诸岛', value: 0 }
      ],
      // 城市数据
      cityData: [],
      // 区县数据
      districtData: [],
      // 当前地图名称
      mapData: []
    }
  },
  watch: {
    regionList: {
      handler(newVal, oldVal) {
        newVal.forEach(item => {
          this.provinceData.forEach(province => {
            if (province.name === item.provinceName) {
              province.value = item.num
            }
          })
          this.getProvinceData()
        })
      },
      deep: true
    }
  },
  async mounted() {
    await this.loadMapData()
    this.initChart()
    window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
  },
  methods: {
    async loadMapData() {
      try {
        const response = await fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${this.currentAdcode}.json`)
        if (!response.ok) {
          throw new Error('Network response was not ok')
        }
        const data = await response.json()
        echarts.registerMap(this.currentMap, data)
      } catch (error) {
        console.error('Failed to load map data:', error)
      }
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('chinaMap'))
      // 获取省份数据
      this.getProvinceData()
      // this.renderChart(this.currentMap)
    },
    renderChart(mapName, series = []) {
      const option = {
        title: {
          text: `${mapName} 数据展示`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.name}<br/>${params.value ? params.value : 0}人`
          }
        },
        visualMap: {
          left: 'left',
          top: 'bottom',
          text: ['高', '低'],
          calculable: true,
          min: 0,
          max: 100,
          // inRange: {
          //   color: ['#ffffff','#FFEFD5','#FFD700','#ff0000']
          // },
          type: 'continuous',
          inRange: { color: ['#ffffff','#ff0000','#6b2113','#4b0000'] },

          // type: 'piecewise',
          // pieces: [
          //   { gte: 0, lt: 1, label: '0-1', color: '#F7F7F7' }, // 灰色
          //   { gte: 1, lt: 50, label: '1-10', color: '#FFEFD5' }, // 淡橙色
          //   { gte: 50, lt: 100, label: '10-20', color: '#FFD700' }, // 金色
          //   { gte: 100, lt: 1000, label: '20-30', color: '#FFA500' }, // 橙色
          //   { gte: 1000, label: '30+', color: '#FF6347' } // 红色
          // ]
        },
        series: series
      }
      this.chart.setOption(option, true)

      // 点击省份时切换到该省的地图
      this.chart.on('click', async(params) => {
        return
        let properties = echarts.getMap(this.currentMap).geoJSON.features.map(item => item.properties)
        let selectedArea = properties.find(item => item.name === params.name)
        if (selectedArea) {
          if (this.currentLevel === 'country' || selectedArea.childrenNum !== 0) {
            this.previousAdcode.push(this.currentAdcode) // 保存上一次的行政代码
            this.previousMap.push(this.currentMap) // 保存上一次的地图名称
            this.previousLevel.push(this.currentLevel) // 保存上一次的级别
          }
          this.currentMap = selectedArea.name // 更新当前地图名称
          if (selectedArea.childrenNum === 0) {
            this.currentAdcode = selectedArea.adcode // 更新行政编码
          } else {
            this.currentAdcode = selectedArea.adcode + '_full' // 更新行政编码
          }
          this.loadMapData().then(() => {
            if (selectedArea.level === 'province') {
              this.currentLevel = 'province' // 更新级别
              console.log('切换到省级:获取其下城市数据')
              this.getCityData()
            } else if (selectedArea.level === 'city') {
              this.currentLevel = 'city' // 更新级别
              console.log('切换到市级:获取其下区域数据')
              this.getDistrictData()
            }
          })
        }
      })
    },
    // 返回上一级区域
    goToPreviousArea() {
      if (this.previousAdcode.length > 0) {
        this.currentAdcode = this.previousAdcode.pop() // 弹出上一次的行政代码
        this.currentMap = this.previousMap.pop() // 弹出上一次的地图名称
        this.currentLevel = this.previousLevel.pop() // 弹出上一次的级别
        this.loadMapData().then(() => {
          if (this.currentLevel === 'country') {
            this.getProvinceData()
          } else if (this.currentLevel === 'province') {
            this.getCityData()
          } else if (this.currentLevel === 'city') {
            this.getDistrictData()
          }
        })
      }
    },
    //返回中国
    goToChinaMap() {
      this.currentMap = '中国' // 返回中国地图
      this.currentAdcode = '100000_full' // 重置行政代码
      this.currentLevel = 'country' // 重置级别
      this.previousAdcode = [] // 重置上一次的行政代码
      this.previousMap = [] // 重置上一次的地图名称
      this.previousLevel = [] // 重置上一次的级别
      this.loadMapData().then(() => {
        this.getProvinceData()
        // this.renderChart(this.currentMap) // 重新渲染中国地图
      })
    },
    // 获取省份数据
    getProvinceData() {
      this.mapData = this.provinceData.map(item => {
        return {
          name: item.name,
          adcode: item.adcode,
          value: item.value
        }
      })
      let series = [
        {
          name: '省份数据',
          type: 'map',
          mapType: this.currentMap,
          roam: false,
          zoom: 1.2,
          emphasis: {
            zoom: 1.5
          },
          data: this.mapData.map((item) => {
            if (item.name === '南海诸岛') {
              return {
                name: item.name,
                value: 0,
                itemStyle: { opacity: 0 }
              }
            }
            return {
              ...item,
              value: item.value ? item.value : 0
            }
          })
        }
      ]
      this.renderChart(this.currentMap, series)
    },
    // 获取城市数据
    getCityData() {
      console.log('获取城市数据')
      let properties = echarts.getMap(this.currentMap).geoJSON.features.map(item => item.properties)
      this.cityData = properties.map(item => {
        return {
          name: item.name,
          adcode: item.adcode,
          value: item.value ? item.value : 99
        }
      })
      this.mapData = this.cityData
      let series = [
        {
          name: '城市数据',
          type: 'map',
          mapType: this.currentMap,
          roam: true,
          data: this.mapData
        }
      ]
      this.renderChart(this.currentMap, series)
    },
    // 获取区县数据
    getDistrictData() {
      console.log('获取区县数据')
      let properties = echarts.getMap(this.currentMap).geoJSON.features.map(item => item.properties)
      this.districtData = properties.map(item => {
        return {
          name: item.name,
          adcode: item.adcode,
          value: item.value ? item.value : 12
        }
      })
      this.mapData = this.districtData
      let series = [
        {
          name: '区县数据',
          type: 'map',
          mapType: this.currentMap,
          roam: true,
          data: this.mapData
        }
      ]
      this.renderChart(this.currentMap, series)
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
#chinaMap {
  width: 100%;
  height: 600px;
}

button {
  margin-top: 10px;
  padding: 10px;
  background: #3498db;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>
